import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/*
 * @lc app=leetcode.cn id=102 lang=java
 *
 * [102] 二叉树的层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private void helper(TreeNode root) {
        System.out.println("-----------------------------------");
        if (root == null) 
            return ;
        Queue<TreeNode> qt = new LinkedList<>();
        qt.offer(root);
        while (!qt.isEmpty()) {
            TreeNode curNode = qt.peek();
            qt.poll();
            System.out.println(curNode.val);

            if (curNode.left != null)
                qt.offer(curNode.left);
            if (curNode.right != null)
                qt.offer(curNode.right);
        }
        System.out.println("---------------------------------");
    }

    public List<List<Integer>> levelOrder(TreeNode root) {

        //test code//
        /*
        System.out.println("-----------------------------------");
        Queue<TreeNode> qt = new LinkedList<>();
        qt.offer(root);
        while (!qt.isEmpty()) {
            TreeNode curNode = qt.peek();
            qt.poll();
            System.out.println(curNode.val);

            if (curNode.left != null)
                qt.offer(curNode.left);
            if (curNode.right != null)
                qt.offer(curNode.right);
        }
        System.out.println("---------------------------------");
        */

        List<List<Integer>> res = new ArrayList<>();

        if (root == null)
            return res;

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {

            int size = q.size();
            List<Integer> level = new LinkedList<>();

            for (int i = 0; i < size; i++) {
   
                TreeNode cur = q.peek();
                q.poll();

                level.add(cur.val);

                if (cur.left != null)
                    q.offer(cur.left);

                if (cur.right != null)
                    q.offer(cur.right);
            }
            res.add(level);
        }

        return res;
    }
}
// @lc code=end

